package net.mihome.app.utils;

import com.loopj.android.http.AsyncHttpResponseHandler;

import net.mihome.app.bean.net.GsonUtils;
import net.mihome.app.bean.net.ResponsePojo;

import org.apache.http.Header;

public abstract class MiAsyncHttpResponseHandler<T> extends AsyncHttpResponseHandler {
	@Override
	public void onFailure(int code, Header[] headers, byte[] jsonResponse, Throwable arg3) {
        arg3.printStackTrace();
		onFailure(code,headers,new Exception(arg3.getMessage()));
	}

	@Override
	public void onSuccess(int code, Header[] headers, byte[] jsonResponse) {
		if(jsonResponse==null||jsonResponse.length<1){
			onFailure(code,headers,new Exception("服务器或网络异常，请稍后再试"));
		}else{
			String jsonString=new String(jsonResponse);
			try{
				GsonUtils<T> gsonUtils=new GsonUtils<T>();
				ResponsePojo<T> responsePojo=gsonUtils.fromJson(jsonString);
				if(responsePojo==null){
					new Exception("服务器或网络异常，请稍后再试");
				}
				else if(responsePojo.getStatus()<0){
//					throw new Exception(responsePojo.getMsg());
                    onFailure(responsePojo.getStatus(),headers,new Exception(responsePojo.getMsg()));
				}else{
					onSuccess(code, headers, responsePojo);
				}
			}catch(Exception e){
				onFailure(code,headers,new Exception(e.getMessage()));
			}
		}
	}
	public abstract void onSuccess(int arg0, Header[] arg1,ResponsePojo<T> responsePojo);
	public abstract void onFailure(int arg0, Header[] arg1, Throwable arg3);
}
